from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse, FileResponse
from django.conf import settings
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
import io, re, json, datetime, os
from order.models import *
from user.models import *
from room.models import *
from .models import *

# Create your views here.
@csrf_exempt
def create_contract(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            oid = data_json.get('oid', 0)
            user = User.objects.get(username=username)
            if not Order.objects.filter(id=oid).exists():
                return JsonResponse({'errno': 1004, 'msg': "订单不存在"})
            order = Order.objects.get(id=oid)
            if order.rent == 1:
                return JsonResponse({'errno': 1005, 'msg': "短期租用无需生成合同"})
            elif order.status == 2:
                return JsonResponse({'errno': 1006, 'msg': "订单已到期"})
            elif order.uid != user.id:
                return JsonResponse({'errno': 1007, 'msg': "登录信息错误"})
            else:
                user_info = UserInfo.objects.get(id=user.id)
                room = Room.objects.get(id=order.rid)
                contract = Contract()
                contract.uid=order.uid
                contract.rid=order.rid
                contract.oid = order.id
                contract.period=order.period
                order.ctid = contract.id
                contract.pdf_path = create_pdf(user_info.name, user_info.id_number,
                           room.address, room.size, order.period, room.price)
                contract.save()
                return JsonResponse({'errno': 0, 'msg': "合同创建成功", 'cid': contract.id})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def get_pdf(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            ctid = data_json.get('ctid', 0)
            uid = User.objects.get(username=username).id
            if not Contract.objects.filter(id=ctid).exists():
                return JsonResponse({'errno': 1004, 'msg': "合同不存在"})
            contract = Contract.objects.get(id=ctid)
            if contract.uid == uid:
                pdf_path = contract.pdf_path
                response = FileResponse(open(pdf_path, 'rb'),
                                        filename='contract_{}'.format(os.path.basename(pdf_path)), as_attachment=True)
                response['Content-Type'] = "application/pdf"
                return response
            else:
                return JsonResponse({'errno': 1003, 'msg': "登录信息错误"})
    else:
       return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})
    # contract = Contract.objects.get(id=2)
    # pdf_path = contract.pdf_path
    # pdf = open(pdf_path, 'rb')
    # response = FileResponse(pdf, filename='contract.pdf', as_attachment=True)
    # response['Content-Type'] = "application/octet-stream"
    # response['Content-Length'] = os.path.getsize(pdf_path)
    # return response

@csrf_exempt
def search_contracts(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        user = User.objects.get(username=username)
        if user.admin:
            res = []
            for contract in Contract.objects.all():
                res.append(contract.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
        else:
            res = []
            for contract in Contract.objects.filter(uid=user.id):
                res.append(contract.get_info())
            return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': res})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def lookup_contract(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        else:
            ctid = data_json.get('ctid', 0)
            user = User.objects.get(username=username)
            if Contract.objects.filter(id=ctid).exists():
                contract = Contract.objects.get(id=ctid)
                if(contract.uid == user.id or user.admin):
                    return JsonResponse({'errno': 0, 'msg': "查询成功", 'content': contract.get_info()})
                else:
                    return JsonResponse({'errno': 1005, 'msg': "用户登录信息错误"})
            else:
                return JsonResponse({'errno': 1004, 'msg': "合同不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})


@csrf_exempt
def delete_contract(request):
    if request.method == 'POST':
        data_json = json.loads(request.body)
        ctid = data_json.get('ctid', 0)
        username = request.session.get('username', "")
        if username == "":
            return JsonResponse({'errno': 1002, 'msg': "请先登录"})
        uid = User.objects.get(username=username).id
        if Contract.objects.filter(id=ctid).exists():
            contract = Contract.objects.get(id=ctid)
            if(contract.uid == uid):
                contract.delete()
                return JsonResponse({'errno': 0, 'msg': "删除合同成功"})
            else:
                return JsonResponse({'errno': 1004, 'msg': "用户登录信息错误"})
        else:
            return JsonResponse({'errno': 1003, 'msg': "合同不存在"})
    else:
        return JsonResponse({'errno': 1001, 'msg': "请求方式错误"})